package com.xncoding.Queue;

import java.util.LinkedList;

public class BlockingDemo {
    static LinkedList<Integer> queue = new LinkedList<Integer>();
    static int maxSize = 5;

    public static void main(String[] args) throws Exception {
        new Thread("生产者") {
            public void run() {
                while (true) {
                    synchronized (queue) {
                        while (queue.size() >= maxSize) {
                            try {
                                System.out.println("队列满了。。。");
                                queue.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        queue.addLast(1);
                        queue.notify();
                        System.out.println("队列中添加了一个元素, size=" + queue.size());
                    }
                }
            };
        }.start();

        new Thread("消费者") {
            public void run() {
                while (true) {
                    synchronized (queue) {
                        while (queue.size() <= 0) {
                            try {
                                System.out.println("队列空了。。。");
                                queue.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        queue.removeFirst();
                        queue.notify();
                        System.out.println("队列中删除了一个元素, size=" + queue.size());
                    }
                }
            };
        }.start();
    }
}
